/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package jlxy.ise.eroad.service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import jlxy.ise.eroad.controller.Bean.CdKeyBean;
import jlxy.ise.eroad.controller.Bean.ComRegisterBean;
import jlxy.ise.eroad.controller.Bean.DetailOrderBean;
import jlxy.ise.eroad.controller.Bean.DetailSearchBean;
import jlxy.ise.eroad.controller.Bean.JJlistBean;
import jlxy.ise.eroad.controller.Bean.JOrderListBean;
import jlxy.ise.eroad.controller.Bean.WaitBean;
import jlxy.ise.eroad.service.function.ClientFunc;
import jlxy.ise.eroad.service.function.CompanyBean;
import jlxy.ise.eroad.service.function.MockNum;
import jlxy.ise.eroad.service.function.PackageBean;
import jlxy.ise.eroad.util.SqlOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author hcc25_000
 */
@Service
@Transactional
public class CompanyService {

    @Autowired
    private SqlOperator sql;

    //获取系统时间
    public String getLocalTime() {
        Date date = new Date();
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");

        return format.format(date);
    }

    public int getMins(String str) {
        String res[] = str.split(" ");
        String year = res[0].split("-")[0];
        int year1 = Integer.parseInt(year);
        int[] array = null;
        if ((year1 % 4 == 0 && year1 % 100 != 0) || year1 % 400 == 0) {
            array = new int[]{31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        } else {
            array = new int[]{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        }
        String month = res[0].split("-")[1];
        String day = res[0].split("-")[2];
        String hour = res[1].split("-")[0];
        String min = res[1].split("-")[1];
        int month1 = Integer.parseInt(month);
        int day1 = Integer.parseInt(day);
        int hour1 = Integer.parseInt(hour);
        int min1 = Integer.parseInt(min);
        int count = 0;
        for (int i = 0; i < month1 - 1; i++) {
            count += array[i];
        }
        int total = (count + day1) * 24 * 60 + (hour1 * 60) + min1;
        return total;
    }

    //公司注册
    public Status ComRegister(String username, String passwd, String cprovince, String ccity, String cdistrict, String caddr) {
        String stmt = "insert into client(username,passwd,cprovince,ccity,cdistrict,caddr) values(?,?,?,?,?,?)";
        Status st = new Status();
        /*String id = this.sql.insert(stmt, username, passwd)[0];
         if (id != null) {
         st.setStatus("ok");
         }*/
        String sm = "select * from client where username=?";
        List list = this.sql.query(sm, username);
        if (!list.isEmpty()) {
            st.setStatus("no");
        } else {
            String id = this.sql.insert(stmt, username, passwd, cprovince, ccity, cdistrict, caddr)[0];
            if (id != null) {
                st.setStatus("ok");
            }
        }
        return st;
    }

    //公司登录
    public Status ComLogin(String username, String passwd) {
        String stmt = "select * from client where username=? and passwd=?";
        Status st = new Status();
        List list = this.sql.query(stmt, username, passwd);
        if (list.isEmpty()) {
            st.setStatus("no");
        } else {
            st.setStatus("ok");
        }
        return st;
    }

    //提交订单
    public Status Allocate(PackageBean pb) {
        String sprovince = pb.getSprovince();
        String scity = pb.getScity();
        String sdistrict = pb.getSdistrict();
        String saddr = pb.getSaddr();
        String stime = pb.getStime();
        String info = pb.getInfo();

        String eprovince = pb.getEprovince();
        String ecity = pb.getEcity();
        String edistrict = pb.getEdistrict();
        String eaddr = pb.getEaddr();
        String etime = pb.getEtime();

        int price = pb.getPrice();
        int timelimit = pb.getTimelimit();
        String cname = pb.getCname();
        String ctel = pb.getCtel();
        String releasetime = getLocalTime();

        Status st = new Status();
        String stmt = "insert into Package(sprovince,scity,sdistrict,saddr,stime,info,eprovince,ecity,edistrict,eaddr,etime,price,timelimit,cname,ctel,releasetime) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        String id = this.sql.insert(stmt, sprovince, scity, sdistrict, saddr, stime, info, eprovince, ecity, edistrict, eaddr, etime, price, timelimit, cname, ctel, releasetime)[0];
        if (id != null) {
            st.setStatus("ok");
        }
        return st;
    }

    //打开竞价中的订单列表
    public List getJOrderList() {
        String stmt = "select id,timelimit,releasetime from Package where flag=2";
        String time = this.getLocalTime();
        int smin = this.getMins(time);
        List list = this.sql.query(stmt);
        Map m = null;
        for (int i = 0; i < list.size(); i++) {
            m = (Map) list.get(i);
            int fmin = this.getMins((String) m.get("releasetime"));
            int timelimit = (Integer) m.get("timelimit");
            int id = Integer.valueOf(m.get("id").toString());
            int timeoff = timelimit - (smin - fmin);
            if (timeoff <= 0) {
                String res = "update Package set flag=3,lefttime=? where id=?";
                this.sql.update(res, 0, id);
            } else {
                String res = "update Package set lefttime=? where id=?";
                this.sql.update(res, timeoff, id);
            }
        }

        String st = "select id,cname,sprovince,scity,sdistrict,stime,info,price,releasetime,lefttime from Package where flag=2";
        List res = this.sql.query(st);

        //代写，先用假数据模拟竞价的司机
        for (int j = 0; j < res.size(); j++) {
            Map map = (Map) res.get(j);
            int fid = Integer.valueOf(map.get("id").toString());
            for (int k = 0; k < 3; k++) {
                String carnum = MockNum.getCarNum();
                double credit = MockNum.getCredit();
                String del = MockNum.getDel();
                int price = MockNum.getPrice();
                String sm = "insert into car(fid,carnum,credit,detel,cprice) values(?,?,?,?,?)";
                this.sql.insert(sm, fid, carnum, credit, del, price);
            }
        }
        //代写
        return res;
    }

    //获取订单详情
    public DetailOrderBean getDetailedOrder(int id) {
        String stmt = "select sprovince,scity,sdistrict,saddr,stime,info,eprovince,ecity,edistrict,eaddr,etime,price,cname,ctel from Package where id=?";
        List list = this.sql.query(stmt, id);
        DetailOrderBean dob = new DetailOrderBean();//新建返回的json类
        if (!list.isEmpty()) {
            Map m = (Map) list.get(0);
            dob.setCname((String) m.get("cname"));
            dob.setCtel((String) m.get("ctel"));
            dob.setEaddr((String) m.get("eaddr"));
            dob.setEcity((String) m.get("ecity"));
            dob.setEdistrict((String) m.get("edistrict"));
            dob.setEprovince((String) m.get("eprovince"));
            dob.setEtime((String) m.get("etime"));
            dob.setInfo((String) m.get("info"));
            dob.setPrice((Integer) m.get("price"));
            dob.setSaddr((String) m.get("saddr"));
            dob.setScity((String) m.get("scity"));
            dob.setSdistrcit((String) m.get("sdistrict"));
            dob.setSprovince((String) m.get("sprovince"));
            dob.setStime((String) m.get("stime"));
        }
        return dob;
    }

    //竞价详情
    public JJlistBean getJJlist(int id) {
        String sm = "select sprovince,scity,sdistrict,saddr,stime,info,price,releasetime,lefttime from Package where id=? and flag=2";
        List list = this.sql.query(sm, id);
        String st = "select cid,carnum,credit,detel,cprice from car where fid=?";
        List res = this.sql.query(st, id);
        JJlistBean jlb = new JJlistBean();
        if (!list.isEmpty()) {
            Map m = (Map) list.get(0);
            jlb.setInfo((String) m.get("info"));
            jlb.setLefttime((Integer) m.get("lefttime"));
            jlb.setPrice((int) m.get("price"));
            jlb.setReleasetime((String) m.get("releasetime"));
            jlb.setSaddr((String) m.get("saddr"));
            jlb.setScity((String) m.get("scity"));
            jlb.setSdistrict((String) m.get("sdistrict"));
            jlb.setStime((String) m.get("stime"));
            jlb.setSprovince((String) m.get("sprovince"));
            jlb.setCarList(res);
        }
        return jlb;
    }

    //选择车辆返回货物编号
    public CdKeyBean SelectCar(int cid) {
        String sm = "select fid from car where cid=?";
        List list = this.sql.query(sm, cid);
        Map m = (Map) list.get(0);
        int fid = (int) m.get("fid");
        String oid = ClientFunc.getCDKey1();
        String st = "update Package set oid=?,flag=1 where id=?";
        this.sql.update(st, oid, fid);
        String stmt = "select cid from car where fid=?";
        List res = this.sql.query(stmt, fid);
        for (int i = 0; i < res.size(); i++) {
            Map map = (Map) res.get(i);
            int key = Integer.valueOf(map.get("cid").toString());
            String smt = "update car set fid=0 where cid=?";
            this.sql.update(smt, key);
        }
        String stm = "update car set fid=? where cid=?";
        this.sql.update(stm, fid, cid);
        CdKeyBean cb = new CdKeyBean();
        cb.setOid(oid);
        cb.setStatus("ok");
        return cb;
    }

    //查看进行中的订单和已经完成的订单
    public List OrderList() {
        String stmt = "select id,oid,cname,sprovince,scity,sdistrict,stime,eprovince,ecity,edistrict,etime,info,flag from Package where oid is not null";
        //判断货物编号不为空值的记录,至于到底是哪种类型由前台判断返回的flag值确定
        List list = this.sql.query(stmt);
        for (int i = 0; i < list.size(); i++) {
            Map m = (Map) list.get(i);
            int id = Integer.valueOf(m.get("id").toString());
            String sm = "select carnum from car where fid=?";
            List ls = this.sql.query(sm, id);
            if (!ls.isEmpty()) {
                Map map = (Map) ls.get(0);
                String carnum = (String) map.get("carnum");
                m.put("carnum", carnum);
            }
        }
        return list;
    }

    //取消订单的操作，取消之后订单过期不再显示
    public Status CancelOrder(int id) {
        Status st = new Status();
        String stmt = "update Package set flag=3,oid=null,lefttime=0 where id=?";//设置该订单的状态为失效
        this.sql.update(stmt, id);
        //修改司机表,重置fid为0
        String sm = "select cid from car where fid=?";
        List list = this.sql.query(sm, id);
        String smt = "update car set fid=0 where cid=?";
        if (!list.isEmpty()) {
            for (int i = 0; i < list.size(); i++) {
                Map m = (Map) list.get(i);
                int key = Integer.valueOf(m.get("cid").toString());
                this.sql.update(smt, key);
            }
        }
        //
        st.setStatus("ok");
        return st;
    }

    //确定完成订单的操作，设置flag=0
    public Status ConfirmOrder(int id) {
        Status st = new Status();
        String stmt = "update Package set flag=0,lefttime=0 where id=?";
        this.sql.update(stmt, id);
        st.setStatus("ok");
        return st;
    }

    //通过订单号查询货物详情
    public DetailSearchBean SearchOrder(String oid) {
        String stmt = "select sprovince,scity,sdistrict,saddr,stime,info,eprovince,ecity,edistrict,eaddr,etime,price,cname,ctel from Package where oid=?";
        List list = this.sql.query(stmt, oid);
        DetailSearchBean dob = new DetailSearchBean();//新建返回的json类
        dob.setParking(0);
        if (!list.isEmpty()) {
            Map m = (Map) list.get(0);
            dob.setCname((String) m.get("cname"));
            dob.setCtel((String) m.get("ctel"));
            dob.setEaddr((String) m.get("eaddr"));
            dob.setEcity((String) m.get("ecity"));
            dob.setEdistrict((String) m.get("edistrict"));
            dob.setEprovince((String) m.get("eprovince"));
            dob.setEtime((String) m.get("etime"));
            dob.setInfo((String) m.get("info"));
            dob.setZprice((Integer) m.get("price"));
            dob.setSaddr((String) m.get("saddr"));
            dob.setScity((String) m.get("scity"));
            dob.setSdistrict((String) m.get("sdistrict"));
            dob.setSprovince((String) m.get("sprovince"));
            dob.setStime((String) m.get("stime"));
            dob.setParking(1);
        }
        String sm = "select id from Package where oid=?";
        List slist = this.sql.query(sm, oid);
        int fid = -1;
        if (!slist.isEmpty()) {
            Map m = (Map) slist.get(0);
            fid = Integer.valueOf(m.get("id").toString());
        }
        String st = "select carnum,detel from car where fid=?";
        List clist = this.sql.query(st, fid);
        if (!clist.isEmpty()) {
            Map m = (Map) clist.get(0);
            dob.setDtel((String) m.get("detel"));
            dob.setCarnum((String) m.get("carnum"));
        }
        return dob;
    }
    //订单查询代写
    //模拟公司注册
    /* public Sret regCompany(ComRegisterBean crb){
     String stmt="insert into com_register(username,passwd,name,phonenum) values(?,?,?,?)";
        
     String username=crb.getUsername();
     String passwd=crb.getPasswd();
     String name=crb.getName();
     String phonenum=crb.getPhonenum();
     String id=this.sql.insert(stmt, username,passwd,name,phonenum)[0];
     Sret sr=new Sret();
     sr.setOk();
     sr.setData(id);
     return sr;
     }
    
     //模拟公司登陆
     public Sret logCompany(CompanyBean cb){
     String stmt="select * from com_register where username=? and passwd=?";
     Sret sr=new Sret();
        
     String username=cb.getUsername();
     String passwd=cb.getPasswd();
        
     List list=this.sql.query(stmt,username,passwd);
        
     if(list.isEmpty()){
     sr.setError();
     sr.setData("用户名或密码错误");
     }else{
     sr.setOk();
     sr.setData(username);
     }
        
     return sr;
     }
    
     //模拟经过平台自动分配后，该公司获得的所有有权限运输的货物信息
     public Sret listAll(String username){
     Sret sr=new Sret();
     String stmt="select * from user_order where comname=?";
        
     List list=this.sql.query(stmt,username);
     if(list.isEmpty()){
     sr.setError();
     sr.setData("没有分配到任何单子");
     }else{
     sr.setOk();
     sr.setData(list);
     }
     return sr;
     }
    
     //获取状态为waiting的货物信息
     //获取状态为running的货物信息---------此处代码还需完善即应该获得司机竞价完成后的那批货物（代写）！！！
     public Sret listWaiting(WaitBean wb){
     Sret sr=new Sret();
     String stmt="select cdkey,time,origin_province,origin_city,origin_district,origin_detailed_address,receiver,receiver_province,receiver_city,receiver_district,receiver_detailed_address from user_order where comname=? and state=?";
        
     String username=wb.getUsername();
     String state=wb.getState();
     List list=this.sql.query(stmt,username,state);
     List data=new LinkedList();
     if(list.isEmpty()){
     sr.setError();
     sr.setData("没有待竞价的货物");
     }else{
     sr.setOk();
     for(int i=0;i<list.size();i++){
     Map m=(Map)list.get(i);
     String origin=""+m.get("origin_province")+""+m.get("origin_city")+""+m.get("origin_district")+""+m.get("origin_detailed_address");
     String receiver=""+m.get("receiver_province")+""+m.get("receiver_city")+""+m.get("receiver_district")+""+m.get("receiver_detailed_address");
     data.add(m.get("cdkey"));
     data.add(m.get("time"));
     data.add(origin);
     data.add(receiver);
     }
     sr.setData(data);
     }
     return sr;
     }
    
     public Sret listRunning(WaitBean wb){
     Sret sr=new Sret();
     String stmt="select cdkey,time,origin_province,origin_city,origin_district,origin_detailed_address,receiver,receiver_province,receiver_city,receiver_district,receiver_detailed_address from user_order where comname=? and state=?";
        
     String username=wb.getUsername();
     String state=wb.getState();
     List list=this.sql.query(stmt,username,state);
     List data=new LinkedList();
     if(list.isEmpty()){
     sr.setError();
     sr.setData("没有正在运输的货物");
     }else{
     sr.setOk();
     for(int i=0;i<list.size();i++){
     Map m=(Map)list.get(i);
     String origin=""+m.get("origin_province")+""+m.get("origin_city")+""+m.get("origin_district")+""+m.get("origin_detailed_address");
     String receiver=""+m.get("receiver_province")+""+m.get("receiver_city")+""+m.get("receiver_district")+""+m.get("receiver_detailed_address");
     data.add(m.get("cdkey"));
     data.add(m.get("time"));
     data.add(origin);
     data.add(receiver);
     }
     sr.setData(data);
     }
     return sr;
     }
    
     //获取状态为finished的货物信息
     public Sret listFinished(WaitBean wb){
     Sret sr=new Sret();
     String stmt="select cdkey,time,origin_province,origin_city,origin_district,origin_detailed_address,receiver,receiver_province,receiver_city,receiver_district,receiver_detailed_address from user_order where comname=? and state=?";
        
     String username=wb.getUsername();
     String state=wb.getState();
     List list=this.sql.query(stmt,username,state);
     List data=new LinkedList();
     if(list.isEmpty()){
     sr.setError();
     sr.setData("没有已经完成运输的货物");
     }else{
     sr.setOk();
     for(int i=0;i<list.size();i++){
     Map m=(Map)list.get(i);
     String origin=""+m.get("origin_province")+""+m.get("origin_city")+""+m.get("origin_district")+""+m.get("origin_detailed_address");
     String receiver=""+m.get("receiver_province")+""+m.get("receiver_city")+""+m.get("receiver_district")+""+m.get("receiver_detailed_address");
     data.add(m.get("cdkey"));
     data.add(m.get("time"));
     data.add(origin);
     data.add(receiver);
     }
     sr.setData(data);
     }
     return sr;
     }
    
     //更改货物状态
     public Sret changeState(String cdkey){
     String stmt="update user_order set state=? where cdkey=?";
     this.sql.update(stmt,"running",cdkey);
     Sret sr=new Sret();
     sr.setData("状态修改完成");
     return sr;
     }*/
}
